package com.atguigu.tingshu.album.api;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencentcloudapi.ame.v20190916.models.Album;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.vod.v20180717.models.MediaInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Map;

@Tag(name = "声音管理")
@RestController
@RequestMapping("api/album/trackInfo")
@SuppressWarnings({"all"})
public class TrackInfoApiController {

    @Autowired
    private TrackInfoService trackInfoService;
    @Autowired
    private AlbumInfoService albumInfoService;
    @Autowired
    private TrackStatMapper trackStatMapper;
    @Autowired
    private VodService vodService;


    /* /api/album/trackInfo/findAlbumTrackPage/{albumId}/{page}/{limit}  */
    @Operation(summary = "分页查询专辑下的声音列表")
    @GetMapping("/findAlbumTrackPage/{albumId}/{page}/{limit}")
    public Result findAlbumTrackPage(@PathVariable("albumId") Long albumId, @PathVariable("page") Long page, @PathVariable("limit") Long limit) {

        //这里要写sql语句了,不能偷懒了，我真的哭了，因为这里又没有vo对象来封装
        Page<Map<String, Object>> mapWithPage = new Page<>(page, limit);
        trackInfoService.findAlbumTrackPage(mapWithPage, albumId);
        return Result.ok(mapWithPage);

    }


    /* /api/album/trackInfo/findUserTrackPage/{page}/{limit}  */
    @Operation(summary = "分页查询用户专辑下的声音")
    @PostMapping("/findUserTrackPage/{page}/{limit}")
    public Result findUserTrackPage(@PathVariable("page") Long page, @PathVariable("limit") Long limit, @RequestBody TrackInfoQuery trackInfoQuery) {

        Page<TrackListVo> trackListWithPage = new Page<>(page, limit);
        Long userId = 1L;
        trackInfoQuery.setUserId(userId);
        trackInfoService.findUserTrackPage(trackListWithPage,trackInfoQuery);

        return Result.ok(trackListWithPage);
    }

    /**
     * http://localhost/api/album/trackInfo/uploadTrack
     */
    @Operation(summary = "上传声音")
    @PostMapping("/uploadTrack")
    public Result uploadTrack(@RequestPart MultipartFile file) {

        JSONObject resultMap = trackInfoService.uploadTrack(file);
        return Result.ok(resultMap);
    }

    /**
     * /api/album/trackInfo/saveTrackInfo
     */
    @Operation(summary = "保存声音")
    @PostMapping("/saveTrackInfo")
    public Result saveTrackInfo(@RequestBody TrackInfoVo trackInfoVo) {

        //两张表  一张trackinfo表，一张track_stat表
        try {
            trackInfoService.saveTrackInfo(trackInfoVo);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return Result.ok();
    }

    /**
     * /api/album/trackInfo/removeTrackInfo/{id}
     */
    @Operation(summary = "删除声音")
    @DeleteMapping("/removeTrackInfo/{id}")
    public Result removeTrackInfo(@PathVariable("id") Long id) {
        //直接在此实现删除声音接口，一共要动三张表，一个statistic表，一个trackinfo表，一个albuminfo表分钟includetracknum

        TrackInfo trackInfo = trackInfoService.getById(id);

        Long albumId = trackInfo.getAlbumId();//查出专辑Id
        AlbumInfo albumInfo = albumInfoService.getById(albumId);//查出要修改的专辑

        albumInfoService.update(new LambdaUpdateWrapper<AlbumInfo>()
                .eq(AlbumInfo::getId, albumId)
                .set(AlbumInfo::getIncludeTrackCount, albumInfo.getIncludeTrackCount() - 1));
        //删除统计表
        LambdaQueryWrapper<TrackStat> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TrackStat::getTrackId, id);
        trackStatMapper.delete(queryWrapper);

        //还需要上根据腾讯云在云点播删除声音根据mediaFileId
        vodService.removeTrackByMediaFileId(trackInfo.getMediaFileId());


        trackInfoService.removeById(id);

        return Result.ok();
    }

    /**
     * /api/album/trackInfo/getTrackInfo/{id}
     */
    @Operation(summary = "根据id查询声音")
    @GetMapping("/getTrackInfo/{id}")
    public Result getTrackInfo(@PathVariable("id") Long id) {
        TrackInfo trackInfo = trackInfoService.getById(id);
        return Result.ok(trackInfo);
    }

    /**
     * /api/album/trackInfo/updateTrackInfo/{id}
     */
    @Operation(summary = "修改声音")
    @PutMapping("/updateTrackInfo/{id}")
    public Result updateTrackInfo(@PathVariable("id") Long id, @RequestBody TrackInfoVo trackInfoVo) {
        //专辑表不用更改，删除才要变动,统计表不受声音表控制
        TrackInfo oldTrackInfo = trackInfoService.getById(id);
        vodService.removeTrackByMediaFileId(oldTrackInfo.getMediaFileId());

        TrackInfo trackInfo = new TrackInfo();
        BeanUtils.copyProperties(trackInfoVo, trackInfo);
        trackInfo.setId(id);
        MediaInfo mediaInfo = vodService.getMediaInfo(trackInfoVo);
        trackInfo.setMediaDuration(mediaInfo.getMetaData().getDuration());
        trackInfo.setMediaUrl(mediaInfo.getBasicInfo().getMediaUrl());
        trackInfo.setMediaSize(mediaInfo.getMetaData().getSize());
        trackInfo.setMediaType(mediaInfo.getBasicInfo().getType());
        trackInfoService.updateById(trackInfo);
        return  Result.ok();
    }




}

